package com.haohan.cloud.scm.purchase.utils;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.haohan.cloud.scm.api.constant.enums.purchase.TaskActionTypeEnum;
import com.haohan.cloud.scm.api.goods.dto.GoodsModelDTO;
import com.haohan.cloud.scm.api.goods.feign.GoodsModelFeignService;
import com.haohan.cloud.scm.api.manage.entity.UPassport;
import com.haohan.cloud.scm.api.manage.feign.UPassportFeignService;
import com.haohan.cloud.scm.api.opc.entity.SummaryOrder;
import com.haohan.cloud.scm.api.opc.feign.SummaryOrderFeignService;
import com.haohan.cloud.scm.api.opc.req.SummaryOrderReq;
import com.haohan.cloud.scm.api.product.entity.ProductInfo;
import com.haohan.cloud.scm.api.product.feign.ProductInfoFeignService;
import com.haohan.cloud.scm.api.product.req.ProductInfoReq;
import com.haohan.cloud.scm.api.product.trans.ProductInfoTrans;
import com.haohan.cloud.scm.api.purchase.entity.PurchaseEmployee;
import com.haohan.cloud.scm.api.purchase.entity.PurchaseOrder;
import com.haohan.cloud.scm.api.purchase.entity.PurchaseOrderDetail;
import com.haohan.cloud.scm.api.purchase.entity.PurchaseTask;
import com.haohan.cloud.scm.api.purchase.req.PurchaseQueryOrderDetailReq;
import com.haohan.cloud.scm.api.purchase.trans.PurchaseInfoTrans;
import com.haohan.cloud.scm.api.supply.entity.OfferOrder;
import com.haohan.cloud.scm.api.supply.entity.Supplier;
import com.haohan.cloud.scm.api.supply.feign.OfferOrderFeignService;
import com.haohan.cloud.scm.api.supply.feign.SupplierFeignService;
import com.haohan.cloud.scm.api.supply.req.AddOfferOrderReq;
import com.haohan.cloud.scm.api.supply.req.OfferOrderReq;
import com.haohan.cloud.scm.api.sys.admin.feign.SystemUserFeignService;
import com.haohan.cloud.scm.api.wms.entity.EnterWarehouse;
import com.haohan.cloud.scm.api.wms.entity.EnterWarehouseDetail;
import com.haohan.cloud.scm.api.wms.feign.EnterWarehouseDetailFeignService;
import com.haohan.cloud.scm.api.wms.feign.EnterWarehouseFeignService;
import com.haohan.cloud.scm.api.wms.req.EnterWarehouseByOrderDetailReq;
import com.haohan.cloud.scm.api.wms.req.EnterWarehouseReq;
import com.haohan.cloud.scm.common.tools.exception.EmptyDataException;
import com.haohan.cloud.scm.common.tools.exception.ErrorDataException;
import com.haohan.cloud.scm.common.tools.util.RUtil;
import com.haohan.cloud.scm.purchase.service.PurchaseEmployeeService;
import com.haohan.cloud.scm.purchase.service.PurchaseTaskService;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import com.pig4cloud.pigx.common.core.util.R;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;

/**
 * @author dy
 * @date 2019/6/12
 */
@Component
@AllArgsConstructor
public class ScmPurchaseUtils {
    private final PurchaseEmployeeService purchaseEmployeeService;
    private final GoodsModelFeignService goodsModelFeignService;
    private final SupplierFeignService supplierFeignService;
    private final ProductInfoFeignService productInfoFeignService;
    private final EnterWarehouseFeignService enterWarehouseFeignService;
    private final EnterWarehouseDetailFeignService enterWarehouseDetailFeignService;
    private final SummaryOrderFeignService summaryOrderFeignService;
    private final PurchaseTaskService purchaseTaskService;
    private final UPassportFeignService uPassportFeignService;
    private final OfferOrderFeignService offerOrderFeignService;
    /**
     * 查询员工信息
     *
     * @param pmId
     * @param uid
     * @return
     */
    public PurchaseEmployee fetchByUid(String pmId, String uid) {
        // 员工
        QueryWrapper<PurchaseEmployee> queryEmployee = new QueryWrapper<>();
        queryEmployee.lambda()
                .eq(PurchaseEmployee::getPmId, pmId)
                .eq(PurchaseEmployee::getPassportId, uid);
        PurchaseEmployee employee = purchaseEmployeeService.getOne(queryEmployee);
        if (null == employee) {
            throw new ErrorDataException("员工有误");
        }
        return employee;
    }

    /**
     * 商品规格信息
     *
     * @param goodsModelId
     * @return
     */
    public GoodsModelDTO fetchGoodsModel(String goodsModelId) {
        R infoById = goodsModelFeignService.getInfoById(goodsModelId, SecurityConstants.FROM_IN);
        if (!RUtil.isSuccess(infoById)) {
            throw new ErrorDataException("GoodsModel为空");
        }
        return BeanUtil.toBean(infoById.getData(), GoodsModelDTO.class);
    }

    /**
     * 新增供应商
     * @param supplier
     * @return
     */
    public Supplier addSupplier(Supplier supplier){
        R r = supplierFeignService.addBuyerSupplier(supplier, SecurityConstants.FROM_IN);
        if (!RUtil.isSuccess(r) || r.getData()==null){
            throw new ErrorDataException("新增供应商失败");
        }
        return BeanUtil.toBean(r.getData(),Supplier.class);
    }

    /**
     * 查询供应商
     *
     * @param supplierId
     * @return 找不到时 null
     */
    public Supplier fetchSupplier(String supplierId) {
        R r = supplierFeignService.getById(supplierId, SecurityConstants.FROM_IN);
        if (!RUtil.isSuccess(r)) {
            throw new ErrorDataException("查询供应商失败");
        } else if (null == r.getData()) {
            return null;
        }
        return BeanUtil.toBean(r.getData(), Supplier.class);
    }

    /**
     * 根据采购单明细 新增货品信息
     * @param req
     * @return
     */
    public ProductInfo addProductInfo(PurchaseQueryOrderDetailReq req){
        R<ProductInfo> r = productInfoFeignService.addProductInfo(req, SecurityConstants.FROM_IN);
        if (!RUtil.isSuccess(r)){
            throw new ErrorDataException("新增货品信息失败");
        }
        return BeanUtil.toBean(r.getData(),ProductInfo.class);
    }

    /**
     * 创建货品信息
     * @param info
     * @return
     */
    public Boolean createProductInfo(ProductInfo info){
        R<ProductInfo> r = productInfoFeignService.save(info, SecurityConstants.FROM_IN);
        if (!RUtil.isSuccess(r)){
            throw new ErrorDataException("新增货品信息失败");
        }
        return true;
    }

    /**
     * 创建入库单明细
     * @param detail
     * @return
     */
    public Boolean createEnterWarehouseDetail(EnterWarehouseDetail detail){
        R<ProductInfo> r = enterWarehouseDetailFeignService.save(detail, SecurityConstants.FROM_IN);
        if (!RUtil.isSuccess(r)){
            throw new ErrorDataException("创建入库单明细失败");
        }
        return true;
    }

    /**
     * 新增入库单（入库单明细）根据采购单明细
     * @param req
     * @return
     */
    public Boolean addEnterWarehouse(EnterWarehouseByOrderDetailReq req){
        R r = enterWarehouseFeignService.enterWarehouseByOrderDetail(req, SecurityConstants.FROM_IN);
        if (!RUtil.isSuccess(r)){
            throw new ErrorDataException("新增入库单失败");
        }
        return true;
    }

    /**
     * 查询汇总单
     * @param req
     * @return
     */
    public SummaryOrder fetchSummaryOrder(SummaryOrderReq req){
        R r = summaryOrderFeignService.getOneBySummaryOrderReq(req, SecurityConstants.FROM_IN);
        if (!RUtil.isSuccess(r)){
            throw new ErrorDataException("查询汇总单失败");
        } else if (null == r.getData()){
            return null;
        }
        return BeanUtil.toBean(r.getData(),SummaryOrder.class);
    }

    /**
     * 修改汇总单
     * @param summaryOrder
     * @return
     */
    public Boolean updateSummaryOrder(SummaryOrder summaryOrder){
        R r = summaryOrderFeignService.updateById(summaryOrder, SecurityConstants.FROM_IN);
        if (!RUtil.isSuccess(r)){
            throw new ErrorDataException("修改汇总单失败");
        }
        return (Boolean) r.getData();
    }

    /**
     * 返回一天开始的时间
     * @return
     */
    public String  todayStart(){
        Calendar todayStart = Calendar.getInstance();
        todayStart.set(Calendar.HOUR_OF_DAY, 0);
        todayStart.set(Calendar.MINUTE, 0);
        todayStart.set(Calendar.SECOND, 0);
        Date time = todayStart.getTime();
        Instant instant = time.toInstant();//An instantaneous point on the time-line.(时间线上的一个瞬时点。)
        ZoneId zoneId = ZoneId.systemDefault();//A time-zone ID, such as {@code Europe/Paris}.(时区)
        return instant.atZone(zoneId).toLocalDateTime().toString().replaceAll("T"," ");
    }

    /**
     * 返回一天结束时间
     * @return
     */
    public String todayEnd(){
        Calendar todayEnd = Calendar.getInstance();
        todayEnd.set(Calendar.HOUR_OF_DAY, 23);
        todayEnd.set(Calendar.MINUTE, 59);
        todayEnd.set(Calendar.SECOND, 59);
        Date time = todayEnd.getTime();
        Instant instant = time.toInstant();//An instantaneous point on the time-line.(时间线上的一个瞬时点。)
        ZoneId zoneId = ZoneId.systemDefault();//A time-zone ID, such as {@code Europe/Paris}.(时区)
        return instant.atZone(zoneId).toLocalDateTime().toString().replaceAll("T"," ");
    }

    /**
     * 查询货品信息，空则创建
     * @param detail
     * @return
     */
    public Boolean queryProductInfo(PurchaseOrderDetail detail){
        ProductInfoReq req = new ProductInfoReq();
        req.setPmId(detail.getPmId());
        req.setPurchaseDetailSn(detail.getPurchaseDetailSn());
        R r = productInfoFeignService.getOneByProductInfoReq(req, SecurityConstants.FROM_IN);
        if(!RUtil.isSuccess(r) || r.getData() == null){
            ProductInfo info = ProductInfoTrans.trans(detail);
            if(!RUtil.isSuccess(productInfoFeignService.save(info, SecurityConstants.FROM_IN))){
                return false;
            }
        }
        return true;
    }

    /**
     * 查询出库单，空则创建
     * @param order
     * @return
     */
    public boolean queryWarehouse(PurchaseOrder order){
        EnterWarehouseReq req = new EnterWarehouseReq();
        req.setPmId(order.getPmId());
        req.setPurchaseSn(order.getPurchaseSn());
        R r = enterWarehouseFeignService.getEnterWarehousePage(req, SecurityConstants.FROM_IN);
        if(!RUtil.isSuccess(r) || r.getData()==null){
            EnterWarehouse warehouse = new EnterWarehouse();
            warehouse.setPmId(warehouse.getPmId());
            warehouse.setPurchaseSn(order.getPurchaseSn());
            if(!RUtil.isSuccess(enterWarehouseFeignService.save(warehouse,SecurityConstants.FROM_IN))){
                return false;
            }
        }
        return true;
    }

    /**
     * 查询采购任务，空就创建
     * @param order
     * @return
     */
    public boolean queryPurchaseTask(PurchaseOrder order){
        QueryWrapper<PurchaseTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(PurchaseTask::getPmId,order.getPmId())
                .eq(PurchaseTask::getPurchaseSn,order.getPurchaseSn())
                .eq(PurchaseTask::getTaskActionType, TaskActionTypeEnum.audit);
        if(purchaseTaskService.getOne(queryWrapper) == null){
            PurchaseTask task = PurchaseInfoTrans.addPurchaseTask(order);
            if(!purchaseTaskService.save(task)){
                return false;
            }
        }
        return true;
    }

    /**
     * 根据id 查询 uPassport
     *
     * @param id
     * @return 可为null
     */
    public UPassport fetchUPassportById(String id) {
        R<UPassport> resp = uPassportFeignService.getById(id, SecurityConstants.FROM_IN);
        if (!RUtil.isSuccess(resp)) {
            throw new EmptyDataException("uPassport查询有误");
        } else if (null == resp.getData()) {
            return null;
        }
        return BeanUtil.toBean(resp.getData(), UPassport.class);
    }

    private final SystemUserFeignService systemUserFeignSerivce;

    /**
     * 查询 用户id
     *
     * @param telephone
     * @return  可为null
     */
    public String fetchUserId(String telephone) {
        R<String> resp = systemUserFeignSerivce.queryUserId(telephone, SecurityConstants.FROM_IN);
        if (!RUtil.isSuccess(resp)) {
            throw new ErrorDataException("用户查询有误");
        }else if (null == resp.getData()) {
            return null;
        }
        return resp.getData();
    }

    /**
     * 新增报价单
     * @param offerReq
     * @return
     */
    public OfferOrder addOfferOrder(AddOfferOrderReq offerReq) {
        R<OfferOrder> resp = offerOrderFeignService.addOfferOrder(offerReq, SecurityConstants.FROM_IN);
        if(!RUtil.isSuccess(resp)){
            throw new ErrorDataException("新增报价单失败");
        }
        return BeanUtil.toBean(resp.getData(), OfferOrder.class);
    }

    /**
     * 查询报价单
     * @param offerReq
     * @return
     */
    public OfferOrder fetchOfferOrder(OfferOrderReq offerReq) {
        R resp = offerOrderFeignService.getOneByOfferOrderReq(offerReq, SecurityConstants.FROM_IN);
        if(!RUtil.isSuccess(resp) || null == resp.getData()){
            throw new ErrorDataException("查询报价单有误");
        }
        return BeanUtil.toBean(resp.getData(), OfferOrder.class);
    }

    /**
     * 修改报价单
     * @param offerReq
     * @return
     */
    public Boolean updateOfferOrder(OfferOrder offerReq) {
        R resp = offerOrderFeignService.updateById(offerReq, SecurityConstants.FROM_IN);
        if(!RUtil.isSuccess(resp) || !(boolean)resp.getData()){
            throw new ErrorDataException("修改报价单失败");
        }
        return true;
    }



}
